package cn.xyinping.pet.service.impl;

import cn.xyinping.basic.exception.MyException;
import cn.xyinping.basic.service.impl.BasicServiceImpl;
import cn.xyinping.pet.domain.Pet;
import cn.xyinping.pet.domain.PetDetail;
import cn.xyinping.pet.mapper.PetDetailMapper;
import cn.xyinping.pet.mapper.PetMapper;
import cn.xyinping.pet.service.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PetServiceImpl  extends BasicServiceImpl<Pet> implements IPetService {

    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;

    @Override
    public void add(Pet pet) {
        // 先存pet,返回自增主键
        petMapper.add(pet);
        // 再存 PetDetail
        PetDetail detail = pet.getDetail();
        detail.setPet_id(pet.getId());
        // 更新
        petDetailMapper.add(detail);
    }


    /**
     * 宠物上架
     * @param ids
     */
    @Override
    public void publish(List<Long> ids) {
        // 判断前端传来的参数不为空
        if(ids==null){
            throw new MyException("请勾选要上架的宠物");
        }
        // 批量查询待上架的宠物状态，宠物状态只有下架才能上架
        List<Pet> pets = petMapper.findByIds(ids,Pet.STATE_OFFLINE);
        // 修改宠物状态为上架, 上架时间
        Date date = new Date();
        pets.forEach(pet -> {
            pet.setState(Pet.STATE_ONLINE);
            pet.setOnsaletime(date);
            petMapper.update(pet);
        });
    }

    /**
     * 宠物下架
     * @param ids
     */
    @Override
    public void offsale(List<Long> ids) {
        // 判断前端传来的参数不为空
        if(ids==null){
            throw new MyException("请勾选要上架的宠物");
        }
        // 批量查询待下架的宠物状态，宠物状态只有上架架才能下架
        List<Pet> pets = petMapper.findByIds(ids,Pet.STATE_ONLINE);
        // 修改宠物状态为下架, 下架时间
        Date date = new Date();
        pets.forEach(pet -> {
            pet.setState(Pet.STATE_OFFLINE);
            pet.setOffsaletime(date);
            petMapper.update(pet);
        });
    }

    /**
     * 查询上架宠物展示详情
     * @param id
     * @return
     */
    @Override
    public Pet selectOnLineById(Long id) {
        return petMapper.loadByIdAndState(id,Pet.STATE_ONLINE);
    }
}
